package org.apache.shiro.web.filter.user;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.liwbn.rbac.common.conf.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import java.io.Serializable;

/**
 * 用户验证过滤器,此处可以根据用户状态处理
 * Created by liwb on 2016-7-25.
 */
public class SysUserFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest,
            ServletResponse servletResponse, Object mappedValue)
            throws Exception {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        if (subject == null || session == null || !subject.isAuthenticated()
                || !subject.isRemembered()) {
            return true;
        }
        // 将principal放置到session中
        Object currentUser = session.getAttribute(Constants.CURRENT_USER);
        if (currentUser == null) {
            Object principal = subject.getPrincipal();
            session.setAttribute(Constants.CURRENT_USER, principal);
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest,
            ServletResponse servletResponse) throws Exception {
        return true;
    }
}
